﻿using System;
using System.Collections.Generic;

namespace Hx.Domain.Repositories.Dapper
{
    public class DapperRepository<TAggregateRoot> : IRepository<TAggregateRoot>
        where TAggregateRoot : class, IAggregateRoot
    {
        private readonly DapperRepositoryContext _dapperContext;

        public DapperRepository(IRepositoryContext context)
        {
            _dapperContext = context as DapperRepositoryContext;
        }

        public IRepositoryContext Context
        {
            get { return _dapperContext; }
        }

        public DapperRepositoryContext DapperContext
        {
            get { return _dapperContext; }
        }

        public void Add(TAggregateRoot aggregateRoot)
        {
            _dapperContext.Add(aggregateRoot);
        }

        public TAggregateRoot GetByKey(Guid key)
        {
            return _dapperContext.Connection.Get<TAggregateRoot>(new { Id = key });
        }

        public IEnumerable<TAggregateRoot> All()
        {
            return _dapperContext.Connection.QueryList<TAggregateRoot>(null);
        }

        public void Remove(TAggregateRoot aggregateRoot)
        {
            _dapperContext.Delete(aggregateRoot);
        }

        public void Update(TAggregateRoot aggregateRoot)
        {
            _dapperContext.Modify(aggregateRoot);
        }
    }
}